// 居住信息
import { Col, Form, Input, InputNumber, Row, type FormInstance } from 'antd';

import FormAuth from '@/components/FormAuth';
import Select from '@/components/NewSelect';
import { findByCodeList } from '@/services/login';
import { getOptions } from '@/utils';
import { chooseOptions, pattern } from '@/utils/common';
import { useRequest } from 'ahooks';
import { type Gutter } from 'antd/es/grid/row';
import { useEffect, useMemo } from 'react';
import { useIntl, useModel } from 'umi';

const StepLive: React.FC<{
  form: FormInstance<any>;
  gutter?: Gutter | [Gutter, Gutter];
  steps?: number;
  isCenter?: boolean;
  span?: number;
  required?: boolean;
  topTitle?: string;
}> = ({ form, steps, gutter = [20, 0], isCenter, span, required = true, topTitle }) => {
  const intl = useIntl();
  const livingSituationVal = Form.useWatch('livingSituation', form);

  const { step } = useModel('stepModel');
  const cSteps = steps || step;
  const { data } = useRequest(() => {
    return findByCodeList({
      code: 'maritalStatus,educationStatus,occupation,area,scope,livingSituation,mortgageInstitutionType,houseType,rentTime',
    });
  });
  const {
    houseType,
    area = [],
    livingSituation,
    mortgageInstitutionType,
    rentTime,
    scope,
  } = data?.data || {};
  useEffect(() => {
    if (!form.getFieldValue('livingSituation') && livingSituation) {
      form.setFieldValue('livingSituation', livingSituation[0].value);
    }
  }, [livingSituation, form]);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const commonComponents = (label?: string) => {
    return (
      <>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, curValues) => prevValues.addressArea !== curValues.addressArea}
        >
          {({ setFieldValue }) => {
            return (
              <FormAuth
                rules={[{ required }]}
                label={intl.formatMessage({ id: label || 'home.district' })}
                name="addressArea"
                span={span || 12}
              >
                <Select
                  onChange={() => {
                    setFieldValue('addressScope', null);
                  }}
                  placeholder={intl.formatMessage({ id: label || 'home.district' })}
                  options={getOptions(area)}
                />
              </FormAuth>
            );
          }}
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, curValues) => prevValues.addressArea !== curValues.addressArea}
        >
          {({ getFieldValue }) => {
            const addressArea = area.find((item) => item.value == getFieldValue('addressArea'))?.id;
            const list = addressArea
              ? scope.filter((item: any) => {
                  return item.parent == addressArea;
                })
              : [];
            return (
              <FormAuth
                rules={[{ required }]}
                label={intl.formatMessage({ id: 'home.region' })}
                name="addressScope"
                span={span || 12}
              >
                <Select
                  placeholder={intl.formatMessage({ id: 'home.region' })}
                  options={getOptions(list)}
                />
              </FormAuth>
            );
          }}
        </Form.Item>

        <FormAuth
          span={span || 12}
          rules={[{ required }, pattern]}
          label={intl.formatMessage({ id: 'home.street' })}
          name="addressStreet"
        >
          <Input placeholder={intl.formatMessage({ id: 'home.street' })} />
        </FormAuth>

        <FormAuth
          span={span || 12}
          rules={[{ required }, pattern]}
          label={intl.formatMessage({ id: 'home.street_number' })}
          name="addressStreetNo"
        >
          <Input maxLength={50} placeholder={intl.formatMessage({ id: 'home.street_number' })} />
        </FormAuth>

        <FormAuth
          span={span || 12}
          rules={[{ required }, pattern]}
          label={intl.formatMessage({ id: 'home.villa' })}
          name="addressVilla"
        >
          <Input placeholder={intl.formatMessage({ id: 'home.villa' })} />
        </FormAuth>
        <FormAuth
          span={span || 12}
          rules={[{ required }, pattern]}
          label={intl.formatMessage({ id: 'home.seat' })}
          name="addressBuilding"
        >
          <Input placeholder={intl.formatMessage({ id: 'home.seat' })} />
        </FormAuth>
        <FormAuth
          span={span || 12}
          rules={[{ required }, pattern]}
          label={intl.formatMessage({ id: 'home.floor' })}
          name="addressFloor"
        >
          <InputNumber
            maxLength={10}
            controls={false}
            placeholder={intl.formatMessage({ id: 'home.floor' })}
          />
        </FormAuth>

        <FormAuth
          span={span || 12}
          rules={[{ required }, pattern]}
          label={intl.formatMessage({ id: 'home.room' })}
          name="addressRoom"
        >
          <InputNumber
            maxLength={10}
            controls={false}
            placeholder={intl.formatMessage({ id: 'home.room' })}
          />
        </FormAuth>
      </>
    );
  };
  const renderCompontns = useMemo(() => {
    const val = livingSituationVal || form.getFieldValue('livingSituation');
    switch (Number(val)) {
      case 1:
        return {
          word: 'center.rent',
          content: (
            <>
              <FormAuth
                rules={[{ required }]}
                label={intl.formatMessage({ id: 'home.rent' })}
                name="rent"
                span={span || 12}
              >
                <InputNumber
                  prefix="$"
                  style={{ width: '100%' }}
                  controls={false}
                  placeholder={`${intl.formatMessage({ id: 'home.rent' })}`}
                />
              </FormAuth>
              <FormAuth
                rules={[{ required }]}
                label={intl.formatMessage({ id: 'home.housing_condition' })}
                name="houseType"
                span={span || 12}
              >
                <Select
                  placeholder={intl.formatMessage({ id: 'home.housing_condition' })}
                  options={getOptions(houseType)}
                />
              </FormAuth>
              <FormAuth
                rules={[{ required }, pattern]}
                label={intl.formatMessage({ id: 'center.rentTime' })}
                name="rentTime"
                span={span || 12}
              >
                <Select
                  options={getOptions(rentTime)}
                  placeholder={intl.formatMessage({ id: 'center.rentTime' })}
                />
              </FormAuth>

              {commonComponents()}
            </>
          ),
        };
      case 2:
        return {
          word: 'center.tenement',
          content: (
            <>
              <FormAuth
                rules={[{ required }]}
                label={intl.formatMessage({ id: 'home.housing_condition' })}
                name="houseType"
                span={span || 12}
              >
                <Select
                  placeholder={intl.formatMessage({ id: 'home.housing_condition' })}
                  options={getOptions(houseType)}
                />
              </FormAuth>

              <FormAuth
                rules={[{ required }, pattern]}
                label={intl.formatMessage({ id: 'center.loan_amout' })}
                name="ownershipRate"
                span={span || 12}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  controls={false}
                  suffix="%"
                  placeholder={intl.formatMessage({ id: 'center.loan_amout' })}
                />
              </FormAuth>

              {commonComponents('home.s_district')}
              <FormAuth
                span={span || 24}
                rules={[{ required }]}
                label={intl.formatMessage({ id: 'center.has_loan' })}
                name="mortgageFlag"
              >
                <Select
                  placeholder={intl.formatMessage({ id: 'center.has_loan' })}
                  options={chooseOptions.map((item) => {
                    return {
                      ...item,
                      value: item.value.toString(),
                    };
                  })}
                />
              </FormAuth>
              <Form.Item
                noStyle
                shouldUpdate={(prevValues, curValues) =>
                  prevValues.mortgageFlag !== curValues.mortgageFlag
                }
              >
                {({ getFieldValue }) => {
                  const mortgageFlag = getFieldValue('mortgageFlag');
                  if (mortgageFlag == 1) {
                    return (
                      <>
                        <FormAuth
                          span={span || 12}
                          rules={[{ required }]}
                          label={intl.formatMessage({ id: 'home.self_type' })}
                          name="mortgageInstitutionType"
                        >
                          <Select
                            placeholder={intl.formatMessage({ id: 'home.self_type' })}
                            options={getOptions(mortgageInstitutionType)}
                          />
                        </FormAuth>

                        <FormAuth
                          rules={[{ required }]}
                          label={intl.formatMessage({ id: 'center.rest_pay_loan' })}
                          name="mortgageAmount"
                          span={span || 12}
                        >
                          <InputNumber
                            prefix="$"
                            style={{ width: '100%' }}
                            controls={false}
                            placeholder={`${intl.formatMessage({
                              id: 'center.rest_pay_loan',
                            })}`}
                          />
                        </FormAuth>

                        <FormAuth
                          rules={[{ required }]}
                          label={intl.formatMessage({ id: 'center.month_pay_loan' })}
                          name="mortgage"
                          span={span || 12}
                        >
                          <InputNumber
                            prefix="$"
                            min={0}
                            max={999999}
                            style={{ width: '100%' }}
                            controls={false}
                            placeholder={`${intl.formatMessage({
                              id: 'center.month_pay_loan',
                            })}`}
                          />
                        </FormAuth>

                        <FormAuth
                          rules={[{ required }]}
                          label={intl.formatMessage({ id: 'center.ins_name' })}
                          name="mortgageName"
                          span={span || 12}
                        >
                          <Input
                            placeholder={`${intl.formatMessage({
                              id: 'center.ins_name',
                            })}`}
                          />
                        </FormAuth>
                      </>
                    );
                  }
                }}
              </Form.Item>
            </>
          ),
        };
      case 3:
      case 4:
        return {
          word: 'center.live',
          content: <>{commonComponents()}</>,
        };
    }
  }, [
    form,
    livingSituationVal,
    commonComponents,
    houseType,
    intl,
    rentTime,
    mortgageInstitutionType,
    required,
    span,
  ]);

  const { word: title, content } = renderCompontns || {};

  return (
    <>
      {/* 居住信息 */}
      {!isCenter ? (
        <div className="info_right_form_title">
          {cSteps == 1
            ? intl.formatMessage({ id: 'center.choose_live' })
            : intl.formatMessage(
                { id: 'center.write' },
                { label: intl.formatMessage({ id: title }).toLowerCase() },
              )}
        </div>
      ) : (
        <div className="info_right_form_sTitle">
          {topTitle || intl.formatMessage({ id: 'home.live_info' })}
        </div>
      )}
      {cSteps == 1 ? (
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, curValues) =>
            prevValues.livingSituation !== curValues.livingSituation
          }
        >
          {({ getFieldValue }) => {
            const fieldType = getFieldValue('livingSituation');
            return (
              <Row gutter={gutter}>
                {livingSituation?.map((item) => {
                  const { value, name } = item;
                  return (
                    <Col
                      onClick={() => {
                        form.setFieldValue('livingSituation', value);
                      }}
                      className={`box_item ${fieldType == value ? 'box_item_active' : ''}`}
                      span={span || 12}
                      key={name}
                    >
                      <Form.Item>
                        <Input
                          style={{ cursor: 'pointer', border: '1px solid #D1D1D1' }}
                          readOnly
                          value={name}
                        />
                      </Form.Item>
                    </Col>
                  );
                })}
              </Row>
            );
          }}
        </Form.Item>
      ) : (
        <>
          {isCenter ? (
            <FormAuth
              rules={[{ required }]}
              label={intl.formatMessage({ id: 'center.living' })}
              name="livingSituation"
              style={{ marginRight: 15 }}
            >
              <Select
                placeholder={intl.formatMessage({ id: 'center.living' })}
                options={getOptions(livingSituation)}
              />
            </FormAuth>
          ) : null}

          <Row gutter={gutter}>{content}</Row>
        </>
      )}
    </>
  );
};

export default StepLive;
